package com.hs.util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/download")
public class DownLoadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(new File("d:/file", filename)));
        //设置header请求头信息
        resp.setHeader("Content-Disposition","filename="+filename);
        //写入缓冲流里面
        BufferedOutputStream bout=new BufferedOutputStream(resp.getOutputStream());
        //创建byte数组
        byte b[]=new byte[1024];
        int n=0;
        while ((n=bis.read(b))!= -1){
            bout.write(b,0,n);
        }
        bis.close();
        bout.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
